<template>
    <div>
        <h1>customRef</h1>
        <h1>{{keyWord}}</h1>
        <input type="text" v-model="keyWord">
        <h1>{{keyWordCustomRef}}</h1>
        <input type="text" v-model="keyWordCustomRef">
    </div>
</template>

<script lang="ts">
import { defineComponent ,ref,customRef} from 'vue'

export default defineComponent({
    setup () {
        const keyWord = ref('');
        const keyWordCustomRef = useCustomRef('');
        function useCustomRef<T>(value:T,delay = 500){//delay表示延迟多少秒
            return customRef((track,trigger)=>{//track告诉vue追踪数据 trigger告诉vue更新界面
                let timeout:number;
                return{
                    get(){
                        track();
                        return value;
                    },
                    set(newValue:T){
                        clearTimeout(timeout);
                        timeout = setTimeout(()=>{
                            value = newValue;
                            trigger();
                        },delay)
                    }
                }
            })
        }
        return {
            keyWord,
            keyWordCustomRef
        }
    }
})
</script>

<style scoped>

</style>